import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { MenuDataItem } from '@ant-design/pro-layout';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const urlreg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => urlreg.test(path);

const emailreg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;

export const isEmail = (path: string): boolean => emailreg.test(path);

const phonereg = /\d{3}-\d{8}|\d{4}-\{7,8}/;

export const isPhone = (path: string): boolean => phonereg.test(path);

const mobilereg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|19[0|1|2|3|5|6|7|8|9])\d{8}$/;

export const isMobile = (path: string): boolean => mobilereg.test(path);

const portreg = /^([1-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;

export const isPort = (path: string): boolean => portreg.test(path);

const ipreg = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/;

export const isIp = (path: string): boolean => ipreg.test(path);

const numreg = /^(0|[1-9][0-9]*)$/;

export const isNumber = (path: string): boolean => numreg.test(path);

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends Route>(
  router: T[] = [],
  pathname: string,
  menuData: MenuDataItem[],
): T | undefined => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname, menuData)),
  );
  if (authority) {
    if (existMenu(pathname, menuData)) {
      authority.authority = ['admin'];
    } else {
      authority.authority = ['no'];
    }
  }
  if (authority) return authority;
  return undefined;
};

export const existMenu = (path: string, menuData: MenuDataItem[]) => {
  let authority = path == '/';
  if (menuData && menuData.length > 0) {
    menuData.forEach(item => {
      // exact match
      if (item.path === path) {
        authority = true;
      }
      // get children authority recursively
      if (item.routes || item.children) {
        authority = existMenu(path, item.routes || item.children) || authority;
      }
    });
  }
  return authority;
};
export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

export const getToken = () => {
  let c_token = localStorage.getItem("x-auth-token");
  if (c_token) {
    return c_token;
  }
  return "";
};

export const validatorPinyin= async (_: any, value: string) => {
  const promise = Promise;

  var pinyin = /^[A-Za-z0-9_]+$/;

  if (!pinyin.test(value)) {
    return promise.reject("请输入字母或数字或组合");
  }
  return promise.resolve();
};

export const validatorMobile = async (_: any, value: string) => {
  const promise = Promise;
  if ('' == value || undefined == value) {
    return promise.resolve();
  } else if (isMobile(value)) {
    return promise.resolve();
  } else {
    return promise.reject("请输入正确的手机号码！");
  }
};

export const validatorIpPort = async (_: any, value: string) => {
  const promise = Promise;

  var pattIp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/;

  if (!pattIp.test(value)) {
    return promise.reject("请输入正确的ip端口号");
  }
  return promise.resolve();
};


export const paramToString = (params) => {
  let paramstr = "";
  if (params == null) {
    return paramstr;
  } else {
    for (let key in params) {
      paramstr += "&" + key + "=" + params[key];
    }
    paramstr = paramstr.substring(1);
    return paramstr;
  }
};


export const paramToStringRemovePage = (params) => {
  let paramstr = "";
  if (params == null) {
    return paramstr;
  } else {
    for (let key in params) {
      if (key == 'current' || key == "pageSize")
        continue;
      paramstr += "&" + key + "=" + params[key];
    }
    paramstr = paramstr.substring(1);
    return paramstr;
  }
};

/*
* 时间格式化工具 
* 把Long类型的1527672756454日期还原yyyy-MM-dd 00:00:00格式日期   
*/
const pad = (n: any) => n < 10 ? `0${n}` : n;
export const datetimeFormat = (longTypeDate: number) => {
  var dateTypeDate = "";
  var date = new Date();
  date.setTime(longTypeDate);
  dateTypeDate += date.getFullYear(); //年    
  dateTypeDate += "-" + pad(date.getMonth() + 1); //月     
  dateTypeDate += "-" + pad(date.getDate()); //日    
  dateTypeDate += " " + pad(date.getHours()); //时    
  dateTypeDate += ":" + pad(date.getMinutes());  //分  
  dateTypeDate += ":" + pad(date.getSeconds()); //分  
  return dateTypeDate;
}
/*  
 * 时间格式化工具 
 * 把Long类型的1527672756454日期还原yyyy-MM-dd格式日期   
 */
export const dateFormat = (longTypeDate: number) => {
  var dateTypeDate = "";
  var date = new Date();
  date.setTime(longTypeDate);
  dateTypeDate += date.getFullYear(); //年    
  dateTypeDate += "-" + pad(date.getMonth() + 1); //月     
  dateTypeDate += "-" + pad(date.getDate()); //日   
  return dateTypeDate;
}

class Socket {
  private _socket: any;
  init(userid: string | URL) {
    if (this._socket) {
      return
    } else {
      this._socket = new WebSocket('ws://172.16.99.116:8080/ws/' + userid);
    }
  }
  get socket() {
    return this._socket
  }
}
export const mySocket = new Socket();

export function numberConversion (value) {
  if(value<=99999999){
    return  Math.floor(value*100)/ 100
  }
   if(value==null||value==""){
     return "--";
   }
    const newValue = [value, '']
    let fr = 1000
    let num = 3
    let text1 = ''
    let fm = 1
    while (value / fr >= 1) {
      fr *= 10
      num += 1
      // console.log('数字', value / fr, 'num:', num)
    }
    if (num <= 4) { // 千
      newValue[1] = '千';
      newValue[0] = parseInt(value / 1000) + '';
    } else if (num <= 8) { // 万
      text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万'
      // tslint:disable-next-line:no-shadowed-variable
    fm = text1 === '万' ? 10000 : 10000000
      newValue[0] = Math.floor((value / fm)*100)/ 100  + ''
      
      newValue[1] = text1
    } else  { // 亿
      text1 = (num - 8) / 3 > 1 ? '千亿' : '亿'
      text1 = (num - 8) / 4 > 1 ? '万亿' : text1
      text1 = (num - 8) / 7 > 1 ? '千万亿' : text1
      // tslint:disable-next-line:no-shadowed-variable
      fm = 1
      if (text1 === '亿') {
        fm = 100000000
      } else if (text1 === '千亿') {
        fm = 100000000000
      } else if (text1 === '万亿') {
        fm = 1000000000000
      } else if (text1 === '千万亿') {
        fm = 1000000000000000
      }
 
  
      newValue[0] = Math.floor((value / fm)*100)/ 100 + ''
      
      newValue[1] = text1
    }
   
    if (value < 1000) {
      newValue[0] = value + ''
      newValue[1] = ''
    }
 
    return newValue.join('')
  }



//  秒数转化为时分秒
export function formatSeconds(value) {
  //  秒
  let second = parseInt(value)
  //  分
  let minute = 0
  //  小时
  let hour = 0
  //  天
  //  let day = 0
  //  如果秒数大于60，将秒数转换成整数
  if (second > 60) {
    //  获取分钟，除以60取整数，得到整数分钟
    minute = parseInt(second / 60)
    //  获取秒数，秒数取佘，得到整数秒数
    second = parseInt(second % 60)
    //  如果分钟大于60，将分钟转换成小时
    if (minute > 60) {
      //  获取小时，获取分钟除以60，得到整数小时
      hour = parseInt(minute / 60)
      //  获取小时后取佘的分，获取分钟除以60取佘的分
      minute = parseInt(minute % 60)
      //  如果小时大于24，将小时转换成天
      //  if (hour > 23) {
      //    //  获取天数，获取小时除以24，得到整天数
      //    day = parseInt(hour / 24)
      //    //  获取天数后取余的小时，获取小时除以24取余的小时
      //    hour = parseInt(hour % 24)
      //  }
    }
  }
 
  let result = '' ;

  if (second > 0) {
     result = '' + parseInt(second) + '秒'
  }
  if (minute > 0) {
    result = '' + parseInt(minute) + '分' + result
  }
  if (hour > 0) {
    result = '' + parseInt(hour) + '小时' + result
  }

  if(result==''){
    result='0秒';
  }
  //  if (day > 0) {
  //    result = '' + parseInt(day) + '天' + result
  //  }
  console.log('result：', result)
  return result
}
 
